<template>
  <el-dialog
    title="pdf"
    width="960px"
    :visible.sync="dialogVisible"
    class="view-dialog-container"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    lock-scroll
    @close="$emit('close')">
    <div class="content-box" ref="pdfBox">
      <!-- 展示 -->
      <pdf
        class="pdf-inner-box"
        v-for="i in numPages"
        :key="i"
        :src="src"
        :page="i"></pdf>
      <!-- 打印 -->
      <pdf :src="src" class="pdf-print-box" ref="pdfViewer"></pdf>
    </div>
    <div slot="footer" class="dialog-footer-box">
      <div class="btn-box" id="lzc">
        <el-button @click="$emit('close')">关闭</el-button>
        <el-button type="primary" @click="printFn">打印</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
/**
 * 注意点：
 * 1、pdf不设置高度时会报错Rendering cancelled, page 1
 * 2、预览本地文件时，pdf.createLoadingTask加载public里面的文件路径，/代表public文件夹
 *    预览在线文件时，需要解决跨域问题(这个好像很麻烦)
 * 3、vue-pdf-signature就是基于vue-pdf，都支持分页，后者适用于仅需查看 PDF 的场景；前者重点增加了 PDF 签名功能，支持在 PDF 上添加电子签名、手写批注等交互操作
 * 4、预览时用v-for="i in numPages"去循环pdf，打印时只需添加一个pdf，给其src就好，也就是预览和打印分开，
 *    因为目前尝试的结果是，直接用vue-print-nb打印多页区域，不会显示，所以就用元素的dom.print()进行`
 * 5、vue-pdf-signature就是基于vue-pdf，安装前者时，后者也需要安装
 */
import pdf from 'vue-pdf-signature';
export default {
  components: {
    pdf
  },
  data() {
    return {
      dialogVisible: false,
      numPages: null,
      src: null
    };
  },
  mounted() {
    this.dialogVisible = true;
    this.loadPdf();
    this.$nextTick(() => {
      this.$refs.pdfBox.scrollTop = 0;
    });
  },
  methods: {
    loadPdf() {
      let url = '/file/git.pdf';
      // url = '/pdfh5/git.pdf';
      // url = '/pdf?url=https://alist-data96.oss-cn-shanghai.aliyuncs.com/PDF_On_Line.pdf';
      this.src = pdf.createLoadingTask(url, {
        withCredentials: false
      });
      this.src.promise.then(res => {
        this.numPages = res.numPages;
      });
    },
    printFn() {
      this.$refs.pdfViewer.print();
    }
  }
};
</script>

<style lang="scss" scoped>
.view-dialog-container {
  ::v-deep .el-dialog {
    .el-dialog__header {
      border-bottom: 1px solid #ddd;
    }
    .el-dialog__body {
      min-height: 300px;
      overflow-y: auto;
    }
    .el-dialog__footer {
      padding: 20px;
      border-top: 1px solid #ddd;
    }
  }
  .dialog-footer-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    box-sizing: border-box;
  }
  .content-box {
    height: 400px;
    overflow-x: hidden;
    overflow-y: auto;
    margin: auto;
    background-color: #fafafa;
    border-radius: 4px;
    position: relative;
    .pdf-inner-box {
      margin: 16px auto;
      width: 900px;
      height: 1272px;
      border: 1px solid #eee;
      box-sizing: border-box;
      canvas {
        height: 100% !important;
      }
    }
    .pdf-print-box {
      position: absolute;
      z-index: -1;
      left: 999999px;
      top: 0;
      height: 1272px;
    }
  }
}
</style>
